package org.javatribe.calculator.module.handler;

import org.javatribe.calculator.common.EventWrapper;
import org.javatribe.calculator.common.Handler;
import org.javatribe.calculator.module.view.IndexFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.*;

/**
 * Created by Wenxin on 2017/9/16.
 */
public class CalculateHandler implements Handler {

    private static final Logger logger = LoggerFactory.getLogger(CalculateHandler.class);

    @Override
    public void handle(EventWrapper eventWrapper) {
        eventWrapper.proccess();
        IndexFrame indexFrame = (IndexFrame) eventWrapper.getFrame();
        if (eventWrapper.getEvent().getSource().equals(indexFrame.getEQUAL_BUTTON())){
            JTextField text_field = indexFrame.getTEXT_FIELD();
            String expression = text_field.getText();
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine js = manager.getEngineByName("js");
            try {
                Object eval = js.eval(expression);
                text_field.setText(eval.toString());
            } catch (ScriptException e) {
                logger.debug("calculate error",e);
                text_field.setText("ERROR!");
            }

        }
    }
}
